const redis = require('redis')
const {REDIS_CONFIG} = require('../config/db.js')

const redisClient = redis.createClient(REDIS_CONFIG.port,REDIS_CONFIG.host)
redisClient.on('error',err=>{
  return console.error(err)
})

function set(key,val) {
  if (typeof val === 'object'){
    val = JSON.stringify(val)
  }
  redisClient.set(key,val)
}
function get(key) {
  const promise = new Promise((resolve, reject) => {
    redisClient.get(key,(err,val)=>{
      if (err){
        reject(err)
        return
      }
      if (val == null){
         resolve(null)
        return
      }
      //兼容转化格式
      //并非抛出异常
      try{
        resolve(
          JSON.parse(val)
        )
      }catch (e) {
        resolve(val)
      }
    })
  })
  return promise
}
module.exports={
  set,
  get
}